﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor.Operations
{
	internal class NewQuad : Operation
	{
        Engine.Selection Selected;
        Engine.Selection ItemAdded;

        internal NewQuad(Engine.Selection Selected)
		{
			this.Selected = Selected;
		}

		internal override ReturnCode Do(EditorState ES)
		{
            Data.EntityRecord Entity = ES.GetTopObject(Selected) as Data.EntityRecord;
            if (Entity == null) return ReturnCode.DoNotAddToUndoStack;

			//if (!Selected.TopIsEntity()) return ReturnCode.DoNotAddToUndoStack;

			Vector2 Offset = ES.Map.Elements[Selected.TopIndex].GetPosition();
			Data.Quad NewPolygon = new Data.Quad();
            NewPolygon[0].Position = ES.RawMousePosition - Offset;
            NewPolygon[1].Position = ES.RawMousePosition - Offset + new Vector2(4, 0);
            NewPolygon[2].Position = ES.RawMousePosition - Offset + new Vector2(4, 4);
            NewPolygon[3].Position = ES.RawMousePosition - Offset + new Vector2(0, 4);
			//(ES.Map.Elements[Selected.TopIndex] as Data.EntityRecord).AttachedElements.Add(NewPolygon);
            Entity.AttachedElements.Add(NewPolygon);

            ItemAdded = new Engine.Selection(Engine.Selection.Types.EntityElement, Selected.TopIndex,
				Entity.AttachedElements.Count - 1, 0);
            ES.RebuildNode(ItemAdded.TopIndex);
			ES.SelectItem(ItemAdded);

			return ReturnCode.AddToUndoStack;
		}

		internal override void Undo(EditorState ES)
		{
			(ES.Map.Elements[ItemAdded.TopIndex] as Data.EntityRecord).AttachedElements.RemoveAt(ItemAdded.MiddleIndex);
            ES.RebuildNode(ItemAdded.TopIndex);
            ES.SelectItem(new Engine.Selection(Engine.Selection.Types.MapElement, ItemAdded.TopIndex, 0, 0));
		}
	}
}
